package cn.share.life.module.infra.controller.app;

import cn.share.life.common.pojo.R;
import cn.share.life.module.infra.fastdfs.FastDFSClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/upload")
public class UploadController {

    @Value("${FILE_SERVER_URL}")
    private String FILE_SERVER_URL;//文件服务器地址

    @PostMapping("/uploadImg")
    public R upload(@RequestParam(name = "file") MultipartFile file) {
        //1、取文件的扩展名
        String originalFilename = file.getOriginalFilename();
        String extName = null;
        if (originalFilename != null) {
            extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        }
        try {
            //2、创建一个 FastDFS 的客户端
            //3、注意项目不要在中文路径下，否则加载不到这个配置文件。
            FastDFSClient fastDFSClient = new FastDFSClient("classpath:fdfs_client.conf");
            //3、执行上传处理
            String path = fastDFSClient.uploadFile(file.getBytes(), extName);
            //4、拼接返回的 url 和 ip 地址，拼装成完整的 url
            String url = FILE_SERVER_URL + path;
            return R.ok(url);
        } catch (Exception e) {
            return R.fail("上传失败");
        }
    }

}
